package xdu.lz.stage6_threadpool.chapter3_threadPoolExecutorAPI;

import java.util.concurrent.*;

/**
 * Created at 2019/10/24 0024 下午 5:06
 *
 * JDK Future有许多缺点，
 * 1：get阻塞住
 *
 * 2：idDone不能反映更加细节的情况，
 *
 * 见{@link io.netty.util.concurrent.Future}
 * {@link io.netty.channel.ChannelFuture}改进
 */
public class FutureAPITest {

    public static void main(String[] args) {

    }

    private static void testGet(){
        ExecutorService service = Executors.newFixedThreadPool(5);
        Future<String> future = service.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("start the task");
                Thread.sleep(1000);
                return null;
            }
        });

        //当前线程调用的是当前线程被阻塞住，打断的是当前线程而不是执行call方法的线程
        try {
            future.get();
            future.get(500,TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }

    /**
     * Returns {@code true} if this task completed.
     *
     * 缺点如下： 不能准确反映真实情况，
     * 见netty的Future以及ChannelFuture，有是否成功，是否是异常，增加回调等功能。
     *
     * Completion may be due to normal termination, an exception, or
     * cancellation -- in all of these cases, this method will return
     * {@code true}.
     *
     */

    private static void testIsDone(){
        ThreadPoolExecutor service = (ThreadPoolExecutor) Executors.newCachedThreadPool();

        Future<Integer> future = service.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("service = " + service);
                return 1;
            }
        });

        future.isDone();
    }
    /**
     * This attempt will fail if
     * 1、the task has already completed,
     * 2、has already been cancelled,
     * 3、could not be cancelled for some other reason.
     *
     * If successful,isCancelled(),isDone() will always return true
     *
     * 如果任务被cancle，那么返回的结果不会再被拿到。
     */
    private static void testCancle(){
        ThreadPoolExecutor service = (ThreadPoolExecutor) Executors.newCachedThreadPool();

        Future<Integer> future = service.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("service = " + service);
                return 1;
            }
        });

        future.cancel(true);
        future.isCancelled();
        future.isDone();
    }
}
